<template>
  <a-modal
    title-align="start"
    v-model:visible="visible"
    @close="handleCancel(formRef)"
    width="660px"
  >
    <template #title>{{ curId ? '编辑' : '创建' }}</template>
    <a-form  :loading='true' ref="formRef" :model="formData">
      <a-form-item
        field="username"
        label="账号"
        label-col-flex="40px"
        :rules="[{ required: true, message: 'username is required' }]"
        :validate-trigger="['change', 'input']"
      >
        <a-input
          allow-clear
          v-model="formData.username"
          placeholder="请输入账号"
        />
      </a-form-item>
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item
            field="first_name"
            label="姓"
            label-col-flex="40px"
            :rules="[{ required: true, message: 'first_name is required' }]"
            :validate-trigger="['change', 'input']"
          >
            <a-input
              allow-clear
              v-model="formData.first_name"
              placeholder="请输入姓氏"
            /> </a-form-item
        ></a-col>
        <a-col :span="12"
          ><a-form-item
            field="last_name"
            label="名"
            label-col-flex="40px"
            :rules="[{ required: true, message: 'last_name is required' }]"
            :validate-trigger="['change', 'input']"
          >
            <a-input
              allow-clear
              v-model="formData.last_name"
              placeholder="请输入名"
            /> </a-form-item
        ></a-col>
      </a-row>
      <a-row :gutter="16">
        <a-col :span="12"
          ><a-form-item
            field="email"
            label="邮箱"
            label-col-flex="40px"
            :rules="[
            { required: true, message: 'email is required' },
            {
            pattern: /^\w+@[0-9a-z]+\.[a-z]+$/,
            message: '邮箱地址格式不正确, 请输入重新输入'
             }
            ]"
            :validate-trigger="['change', 'input']"
            >
            <a-input
              allow-clear
              v-model="formData.email"
              placeholder="请输入邮箱"
            /> </a-form-item
        ></a-col>
        <a-col :span="12">
          <a-form-item
            field="mobile"
            label="手机"
            label-col-flex="40px"
            :rules="[
            { required: true, message: 'mobile is required' },
            {
            pattern: /^1[3|4|5|6|7|8|9][0-9]{9}$/,
            message: '电话号码格式不正确, 请输入重新输入'
             }
            ]"
            :validate-trigger="['change', 'input']"
          >
            <a-input
              hide-button="false"
              allow-clear
              v-model.number="formData.mobile"
              placeholder="请输入手机号"
            /> </a-form-item
        ></a-col>
      </a-row>
      <a-form-item
        field="post"
        label="岗位"
        label-col-flex="40px"
        :rules="[{ required: true, message: 'post is required' }]"
        :validate-trigger="['change', 'input']"
      >
        <a-select
          allow-clear
          multiple
          :style="{ width: '100%' }"
          placeholder="请选择岗位"
          v-model="formData.post"
        >
          <a-option v-for="item in postList" :key="item.id" :value="item.id">{{
            item.name
          }}</a-option>
        </a-select>
      </a-form-item>
      <a-form-item
        field="dept"
        label="部门"
        label-col-flex="40px"
        :rules="[{ required: true, message: 'dept is required' }]"
        :validate-trigger="['change', 'input']"
      >
        <a-tree-select
          multiple
          :field-names="{ key: 'id', title: 'name', children: 'children' }"
          :data="deptList"
          v-model="formData.dept"
          allow-search
          allow-clear
          placeholder="请选择部门"
        />
      </a-form-item>
      <a-form-item
        field="role"
        label="角色"
        label-col-flex="40px"
        :rules="[{ required: true, message: 'role is required' }]"
        :validate-trigger="['change', 'input']"
      >
        <a-select
          allow-clear
          multiple
          :style="{ width: '100%' }"
          v-model="formData.role"
          placeholder="请选择角色"
        >
          <a-option v-for="item in roleList" :key="item.id" :value="item.id">{{
            item.name
          }}</a-option>
        </a-select>
      </a-form-item>
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item
            field="gender"
            label="性别"
            label-col-flex="40px"
            :rules="[{ required: true, message: 'gender is required' }]"
            :validate-trigger="['change', 'input']"
          >
            <a-radio-group v-model="formData.gender">
              <a-radio :value="1">男</a-radio>
              <a-radio :value="0">女</a-radio>
            </a-radio-group>
          </a-form-item>
          </a-col >
        <a-col :span="12">
          <a-form-item field="is_active" label="状态" label-col-flex="40px">
            <a-switch v-model="formData.is_active" type="round">
              <template #checked> ON </template>
              <template #unchecked> OFF </template>
            </a-switch>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
    <template #footer>
      <a-button @click="visible = false">取消</a-button>
      <a-button type="primary" @click="handleOk">确定</a-button>
    </template>
  </a-modal>
</template>

<script lang="ts" setup>
import { getRoleList, getPostList, getDeptList } from '@/api/list';
import { ref, defineEmits, reactive } from 'vue';
const formRef = ref<any>(null);
const formData = reactive<any>({
  username: '',
  first_name: '',
  last_name: '',
  email: '',
  gender: 1,
  mobile: '',
  is_active: false,
  role: [],
  dept: [],
  post: [],
});
const generateFormModel = () => {
  return {
    search: '',
    page: 1,
    limit: 9999,
  };
};
const formModel = ref(generateFormModel());
const visible = ref(false);
const roleList = ref([]);
const postList = ref([]);
const deptList = ref([]);
const curId = ref('');
const handleClick = async (val: any) => {
 formData.role = []
 formData.dept = []
 formData.post = []
  await fetchData();
  visible.value = true;
  if (val && val.id) {
    curId.value = val.id;
    Object.keys(val).forEach((item: string) => {
      if(item==='role'||item==='post'|| item==='dept'){
       formData[item] = val[item].map((item:any) => item.id)
      }else{
        formData[item] = val[item];
      }
    });
  }
};
const emits = defineEmits(['submitFrom']);
// 获取role post dept
const fetchData = async () => {
 getRoleList(formModel.value).then((res:any) => {
  roleList.value = res.data.item 
 })
  getPostList(formModel.value).then((res:any) => {
  postList.value = res.data.item 
 })
  getDeptList(formModel.value).then((res:any) => {
  deptList.value = res.data
 })
};
// const fetchData = async () => {
//   try {
//     const res1 = await getRoleList(formModel.value);
//     roleList.value = res1.data.item || [];
//     const res2 = await getPostList(formModel.value);
//     postList.value = res2.data.item || [];
//     const res3 = await getDeptList(formModel.value);
//     deptList.value = res3.data || [];
//   } catch (err) {
//     // you can report use errorHandler or other
//   }
// };
const handleOk = async () => {
  console.log('handleOk',handleOk);
  
  const res = await formRef.value?.validate();
  if (!res) {
    emits('submitFrom', formData, curId.value);
  }
};
const handleCancel = (formEl: any) => {
  curId.value = '';
  roleList.value = [];
  deptList.value = [];
  postList.value = [];
  formEl.resetFields();
};
defineExpose({ handleClick, visible });
</script>

<style scoped lang="less">
.title_style {
  color: #ff7d00;
}
</style>
